package com.liuch.mybatis.Utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResultSet2List {
    public static List<Object> resultSetToList(ResultSet rs, Class<?> cls) throws SQLException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        List<Object> list = new ArrayList<>();
        Object obj = null;

        while(rs.next()){
            //实例化
            obj = cls.getDeclaredConstructor().newInstance();
            //获取结果集的数据源
            ResultSetMetaData metaData = rs.getMetaData();
            //获取结果集中的字段数
            int count = metaData.getColumnCount();
            //取出每个字段的名字以及他们的值，并赋给对应的实体类对象
            for (int i = 0; i < count; i++) {
                //得到字段名字
                String columnName = metaData.getColumnName(i + 1);
                //获取字段对象
                Field f = obj.getClass().getDeclaredField(columnName);
                f.setAccessible(true);
                //赋值
                f.set(obj, rs.getObject(columnName));
            }
            list.add(obj);
        }
        return list;
    }
}
